package com.david.viewtest

import android.content.ContentValues
import android.content.res.Resources
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.PixelFormat
import android.graphics.Rect
import android.os.Bundle
import android.os.Looper
import android.provider.MediaStore
import android.text.TextPaint
import android.text.TextUtils
import android.util.TypedValue
import android.view.ViewGroup
import android.view.ViewGroup.MarginLayoutParams
import android.view.WindowManager
import android.widget.FrameLayout
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.res.ResourcesCompat
import androidx.core.graphics.drawable.toBitmap
import androidx.core.view.updateLayoutParams
import com.david.core.utils.StateListDrawableHelper.context
import com.david.viewtest.databinding.LayoutGetshareContentBitmapBinding
import com.david.viewtest.view.CanvasTestView
import com.david.viewtest.view.ShareBitmapCreateView


class CanvasTestActivity: AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_canvas_test)

        findViewById<CanvasTestView>(R.id.canvas_view).setOnClickListener {
            //val bitmap = Bitmap.createBitmap(it.width, it.height, Bitmap.Config.ARGB_8888);
            //val canvas = Canvas(bitmap)
            //it.draw(canvas)
            //
            ////保存图片参考：https://blog.csdn.net/lu202032/article/details/122391286
            ////创建一个保存的Uri
            ////创建一个保存的Uri
            //val saveUri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, ContentValues())
            //if (TextUtils.isEmpty(saveUri.toString())) {
            //    Looper.prepare()
            //    Toast.makeText(this@CanvasTestActivity, "保存失败！", Toast.LENGTH_SHORT).show()
            //    Looper.loop()
            //    return@setOnClickListener
            //}
            //val outputStream = contentResolver.openOutputStream(saveUri!!)
            //
            //
            //
            ////var fos: FileOutputStream? = null
            //try {
            //    //if (!file.exists()) {
            //    //    file.createNewFile()
            //    //}
            //    //fos = FileOutputStream(file)
            //    bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream!!)
            //} catch (e: Exception) {
            //    e.printStackTrace()
            //}
            //try {
            //    outputStream!!.close()
            //} catch (e: Exception) {
            //    e.printStackTrace()
            //}


            val binding = LayoutGetshareContentBitmapBinding.inflate(layoutInflater)
            val contentBitmap = (it as CanvasTestView).longImgBitmap
            //binding.root.updateLayoutParams<MarginLayoutParams> { width = (contentBitmap.width + dp2px(64f)).toInt() }
            binding.contentImg.setImageBitmap(contentBitmap)


            val params = FrameLayout.LayoutParams(
                WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.WRAP_CONTENT)
            //val wm = this@CanvasTestActivity.getSystemService(WINDOW_SERVICE) as WindowManager

            (params as MarginLayoutParams).topMargin = 100000
            binding.contentImg.updateLayoutParams<MarginLayoutParams> { height = contentBitmap.height }
            findViewById<ViewGroup>(android.R.id.content).addView(binding.root, params)


            binding.root.post {
                val bitmap = Bitmap.createBitmap(binding.root.width, binding.root.getChildAt(0).height, Bitmap.Config.ARGB_8888);
                val canvas = Canvas(bitmap)
                binding.root.draw(canvas)



                //保存图片参考：https://blog.csdn.net/lu202032/article/details/122391286
                //创建一个保存的Uri
                //创建一个保存的Uri
                //val saveUri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, ContentValues())
                //if (TextUtils.isEmpty(saveUri.toString())) {
                //    Looper.prepare()
                //    Toast.makeText(this@CanvasTestActivity, "保存失败！", Toast.LENGTH_SHORT).show()
                //    Looper.loop()
                //    return@post
                //}
                //val outputStream = contentResolver.openOutputStream(saveUri!!)



                ////var fos: FileOutputStream? = null
                //try {
                //    //if (!file.exists()) {
                //    //    file.createNewFile()
                //    //}
                //    //fos = FileOutputStream(file)
                //    bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream!!)
                //} catch (e: Exception) {
                //    e.printStackTrace()
                //}
                //try {
                //    outputStream!!.close()
                //} catch (e: Exception) {
                //    e.printStackTrace()
                //}

                findViewById<ViewGroup>(android.R.id.content).removeView(binding.root)







                val desWidth = (this@CanvasTestActivity.resources.displayMetrics.widthPixels + dp2px(16f))

                val topBitmap: Bitmap = ResourcesCompat.getDrawable(resources, R.mipmap.canvas_img_top, null)!!.toBitmap()
                val bottomBitmap: Bitmap = ResourcesCompat.getDrawable(resources, R.mipmap.canvas_img_bottom, null)!!.toBitmap()

                //val longImgBitmap: Bitmap =
                //    BitmapFactory.decodeStream(resources.assets.open("long_img3.png")) //ResourcesCompat.getDrawable(resources, R.drawable.long_img1, null)!!.toBitmap()

                val topImgHeight = (topBitmap.height / topBitmap.width.toFloat() * desWidth).toInt()
                val bottomImgHeight = bottomBitmap.height / bottomBitmap.width.toFloat() * desWidth



                val shareBitmap = Bitmap.createBitmap(desWidth.toInt(), (topImgHeight + bottomImgHeight + bitmap.height).toInt(), Bitmap.Config.RGB_565);
                val shareCanvas = Canvas(shareBitmap)


                val paint = Paint()
                paint.color = Color.parseColor("#FF5841")

                shareCanvas.drawRect(Rect(0, 0, desWidth.toInt(), shareBitmap.height), paint)

                //绘制顶部默认图
                shareCanvas.drawBitmap(
                    topBitmap,
                    Rect(0, 0, topBitmap.width, topBitmap.height),
                    Rect(0, 0, desWidth.toInt(), topImgHeight),
                    paint
                )


                //绘制内容图
                shareCanvas.drawBitmap(
                    bitmap,
                    Rect(0, 0, bitmap.width, bitmap.height),
                    Rect(dp2px(8f).toInt(), topImgHeight, (desWidth - dp2px(8f)).toInt(), topImgHeight + bitmap.height),
                    paint
                )

                bitmap.recycle()

                //绘制底部默认图
                shareCanvas.drawBitmap(bottomBitmap, Rect(0, 0, bottomBitmap.width, bottomBitmap.height), Rect(0, (shareBitmap.height - bottomImgHeight).toInt(), desWidth.toInt(), shareBitmap.height), paint)
                //shareView.draw(shareCanvas)
                //var fos: FileOutputStream? = null






                val saveUri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, ContentValues())
                if (TextUtils.isEmpty(saveUri.toString())) {
                    Looper.prepare()
                    Toast.makeText(this@CanvasTestActivity, "保存失败！", Toast.LENGTH_SHORT).show()
                    Looper.loop()
                    return@post
                }
                val outputStream = contentResolver.openOutputStream(saveUri!!)
                try {
                    //if (!file.exists()) {
                    //    file.createNewFile()
                    //}
                    //fos = FileOutputStream(file)
                    shareBitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream!!)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
                try {
                    outputStream!!.close()
                } catch (e: Exception) {
                    e.printStackTrace()
                }



                //val shareView = ShareBitmapCreateView(this@CanvasTestActivity, null)
                //
                //shareView.longImgBitmap = bitmap
                //
                //
                //findViewById<ViewGroup>(android.R.id.content).addView(shareView, params)
                //
                //
                //shareView.post {
                //
                //
                //    findViewById<ViewGroup>(android.R.id.content).removeView(shareView)
                //
                //}

            }

        }

    }

    fun dp2px(dp : Float): Float{
        val r = Resources.getSystem()
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.displayMetrics)
    }
}